<template>
  <div class="security_settings">
    <div class="items" v-for="(items, i) in state.list" :key="i">
      <span>{{ t(items.text) }}</span>
      <div v-if="items.btns">
        <span v-if="items.type != 10">{{ info[items.value] }}</span>
        <!-- 资金密码 -->
        <span v-else>{{ items.code == 1 ? info[items.value] : "" }}</span>
        <div v-if="items.btns.length > 0">
          <span
            class="bind_btn"
            v-for="(item, j) in items.btns"
            :id="items.text"
            :key="j"
            @click="itemClick(items)"
          >
            {{ t(item.text) }}</span
          >
        </div>
      </div>
    </div>
    <!-- 绑定资金密码弹窗 -->
    <Modal
      v-model:visible="moneyModal"
      :title="t('home_page_bindFundPassword')"
      @close="closeModal"
    >
      <div class="bind_container">
        <nut-form
          label-position="top"
          ref="withdrawFormRef"
          :model-value="moneyFormData"
          :rules="rules"
        >
          <nut-form-item :label="t('home_page_newPassword')" prop="new_password">
            <nut-input
              v-model="moneyFormData.new_password"
              :placeholder="t('home_page_enterNewPassword')"
              :type="eyeOpen1 ? 'text' : 'password'"
              clearable
            >
              <template #right>
                <iconpark-icon
                  @click="eyeOpen1 = !eyeOpen1"
                  color="#A8A8CA"
                  :icon-id="eyeOpen1 ? 'show' : 'hide'"
                  size="1.3rem"
                  class="mr-12"
                ></iconpark-icon>
              </template>
            </nut-input>
          </nut-form-item>
          <nut-form-item
            :label="t('home_page_enterAgainNewPassword')"
            prop="new_password_confirm"
          >
            <nut-input
              v-model="moneyFormData.new_password_confirm"
              :placeholder="t('home_page_enterAgainNewPassword')"
              :type="eyeOpen2 ? 'text' : 'password'"
            >
              <template #right>
                <iconpark-icon
                  @click="eyeOpen2 = !eyeOpen2"
                  color="#A8A8CA"
                  :icon-id="eyeOpen2 ? 'show' : 'hide'"
                  size="1.3rem"
                  class="mr-12"
                ></iconpark-icon>
              </template>
            </nut-input>
          </nut-form-item>
        </nut-form>
        <div>
          <nut-button class="btn_submit" @click="submit">{{
            t("home_page_bind")
          }}</nut-button>
        </div>
      </div>
    </Modal>
    <Toast v-model:visible="showToast">{{ toast_value }}</Toast>
    <!-- <PopForm ref="FormRef" @nextChange="nextChange" @changeTab="changePasswordChangeTab" @submitData="submitData">
        </PopForm> -->
  </div>
</template>

<script setup lang="ts">
// 国际化使用 homepage
import { onMounted, onUnmounted, reactive, ref } from "vue";

import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { User } from "@/store/user";
import Toast from "@/components/Toast.vue";

import { showNotify } from "@nutui/nutui";
import { useI18n } from "vue-i18n";

import { Local } from "@/utils/storage";

import { NetPacket } from "@/netBase/NetPacket";

import { aaa, bbb, getDeviceId, getRandomSign } from "@/net/Utils";
import {IP, updateStorePayPwd} from "@/utils/useStoreMethods";
import { MessageEvent2 } from "@/net/MessageEvent2";
import { NetMsgType } from "@/netBase/NetMsgType";
import H5Websocket from "@/net/Net1";
import { useRouter } from "vue-router";
import { WithdrawValidator, againWithdrawValidator } from "./validator";
const { t } = useI18n();
const router = useRouter();
const userInfo = User(pinia);
const withdrawFormRef = ref();
const showToast = ref(false);
const toast_value = ref("");
const eyeOpen1 = ref(false);
const eyeOpen2 = ref(false);
const { info, roleInfo } = storeToRefs(userInfo);
const moneyModal = ref(false);
const moneyFormData = ref({
  new_password: "",
  new_password_confirm: "",
});
const rules = {
  new_password: [{ validator: WithdrawValidator }],
  new_password_confirm: [
    {
      validator: (val: any) => {
        return againWithdrawValidator(val, moneyFormData.value.new_password);
      },
    },
  ],
};
const state: any = reactive({
  roleInfo: JSON.parse(JSON.stringify(roleInfo.value)),
  info: JSON.parse(JSON.stringify(info.value)),
  first: 1,
  checkPhoneOremail: false,
  params: null,
  type: 0,
  formData: null,
  list: [
    {
      text: "home_page_name",
      value: "real_name",
      btns: [],
      type: 1,
    },
    {
      text: "home_page_account",
      value: "full_name",
      btns: [],
      type: 1,
    },
    {
      text: "home_page_password",
      value: "hideString",

      btns: [{ text: "home_page_modify", icon: "Group39376", value: 1 }],
      type: 3,
    },
    {
      text: "home_page_email",
      value: "email",
      btns: [
        { text: "home_page_bind", icon: "Group39377", value: 0 },
        // { text: '修改', icon: 'Group39376', value: 1 }
      ],
      type: 4,
    },
    {
      text: "home_page_phone_number",
      value: "mobile",
      btns: [
        { text: "home_page_bind", icon: "Group39377", value: 0 },
        // { text: '修改', icon: 'Group39376', value: 1 }
      ],
      type: 5,
    },
    {
      text: "home_page_fundPassword",
      value: "hideString",
      btns: [{ text: "home_page_bind", icon: "Group39376", value: 1 }],
      type: 10,
    },
  ],
});
// 点击修改某一项
const itemClick = (item: any) => {
  if (item.type == 10) {
    if (item.code == 1) {
      router.push({
        name: "modifyWithdraw",
      });
    } else {
      moneyModal.value = true;
    }
    return;
  }
  const urlObj: any = {
    3: "modifyPassWord", // 修改密码
    4: "bindEmail", // 绑定邮箱
    5: "bindPhone", // 绑定手机号
  };
  router.push({
    name: urlObj[item.type],
    params: item,
  });
};

// 关闭资金密码弹窗
const closeModal = () => {
  moneyFormData.value.new_password = moneyFormData.value.new_password_confirm = "";
};

//   修改资金密码确认
const submit = () => {
  withdrawFormRef.value?.validate().then(({ valid, errors }: any) => {
    if (valid) {
      let req = NetPacket.req_bind_or_modify_withdraw_password();
      req.operate_type = 1;
      req.old_password = "";
      req.new_password = moneyFormData.value.new_password;
      req.role_id = roleInfo.value?.id;
      req.step = roleInfo.value?.id;
      req.new_password_confirm = moneyFormData.value.new_password_confirm;
      H5Websocket.sendMessageHandler(req);
    } else {
      console.warn("error:", errors);
    }
  });
};

// 请求是否可以修改或绑定资金密码
const getModifyWithdrawPassword = () => {
  const req = NetPacket.req_open_or_close_withdraw_password();
  req.operate_type = 4;
  req.role_id = roleInfo.value?.id;
  H5Websocket.sendMessageHandler(req);
};

// 修改会员账号和绑定邮箱和绑定手机号
const changeEmailAndPhoneAndAccount = async (params: any, type: number) => {
  let req = NetPacket.req_bind_modify_email();
  // 1为修改会员账号 4 为绑定邮箱 5为绑定手机号
  if (type == 1) {
    req.username = params.account;
  }
  if (type == 4) {
    req.email = params.email;
    req.username = info.value?.full_name;
    req.captcha = params.emailCode;
    state.info.email = params.email;
  }
  if (type == 5) {
    req.email = params.codeValue + params.mobile;
    req.username = info.value?.full_name;
    req.captcha = params.phoneCode;
    state.info.mobile = req.email;
  }

  req.operate_type = params.operate_type;
  req.agent_id = roleInfo.value.id; //Local.get('agentid')
  req.aaa = aaa;
  req.bbb = bbb;
  req.ip = await IP();
  let id = await getDeviceId();
  req.sign = getRandomSign(id);
  H5Websocket.sendMessageHandler(req);
};

// 请求是否可以更改此账号
const getModifyAccount = () => {
  const req = NetPacket.req_can_modify_account();
  req.newusername = info.value?.real_name || "";
  req.operate_type = 1;
  H5Websocket.sendMessageHandler(req);
};
const resetInputHide = () => {
  for (const key in state.formData.list) {
    state.formData.list[key].show = false;
  }
};

// 返回修改密码是否成功或验证手机或邮箱是否绑定
const handleChangePassword = async (res: any) => {
  if (state.checkPhoneOremail) {
    if (res.code == 1) {
      resetInputHide();
      state.formData.buttonText = "home_page_modifyNow";
      state.formData.step = 2;
      state.formData.list.new_password.show = true;
      state.formData.list.new_password_confirm.show = true;
      state.checkPhoneOremail = false;
    }
  } else {
    if (res.code == 1) {
      showNotify.success(t(res.message));
      // FormRef.value.closeDialog()
      await User(pinia).setHasLogin(false);
      Local.remove("user");
      location.href = "/";
    }
  }
};

// 获取后台通知是否可以更改此账号 并监听是否更改成功
const handleModifyAccount = (res: any) => {
  if (state.first == 1) {
    let find = state.list.find((e: any) => e.type == 1);
    if (res.code == 1) {
      find.btns = [{ text: "home_page_modify", icon: "Group39376", value: 1 }];
      // find.value = info.value?.full_name
      state.first = 2;
    } else {
      find.btns = [];
    }
  } else {
    if (res.code == 1) {
      changeEmailAndPhoneAndAccount(state.params, 1);
    }
  }
};
// 返回是否可以进行修改或绑定资金密码
const handleModifyWithdrawPassword = (res: any) => {
  let findWithdrawPassword = state.list.find((e: any) => e.type == 10);
  // 已绑定资金密码
  if (res.code == 1) {
    findWithdrawPassword.code = 1;
    findWithdrawPassword.btns = [
      { text: "home_page_modify", icon: "Group39376", value: 1 },
    ];
  }
  // 未绑定资金密码
  if (res.code == 2) {
    findWithdrawPassword.code = 2;
    findWithdrawPassword.btns = [
      { text: "home_page_bind", icon: "Group39376", value: 1 },
    ];
  }
};

// 返回绑定资金密码 回执
const handleBindOrModifyWithdrawPassword = (res: any) => {
  let findWithdrawPassword = state.list.find((e: any) => e.type == 10);
  if (res.code == 1) {
    // 绑定成功
    console.log("#######--", moneyFormData.value);
    updateStorePayPwd(moneyFormData.value.new_password);

    findWithdrawPassword.code = 1;
    findWithdrawPassword.btns = [
      { text: "home_page_modify", icon: "Group39376", value: 1 },
    ];
    moneyModal.value = false;
    showToast.value = true;
    toast_value.value = "操作成功";
  }
};

onMounted(async () => {
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_can_modify_account,
    handleModifyAccount
  );
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_open_or_close_withdraw_password,
    handleModifyWithdrawPassword
  );

  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_reset_account_password,
    handleChangePassword
  );
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_bind_or_modify_withdraw_password,
    handleBindOrModifyWithdrawPassword
  );
  let findEmail = state.list.find((e: any) => e.type == 4);
  let findPhone = state.list.find((e: any) => e.type == 5);

  if (info.value?.mobile) {
    findPhone.btns = [];
  }
  if (info.value?.email) {
    findEmail.btns = [];
  }
  getModifyAccount();
  getModifyWithdrawPassword();
});
onUnmounted(() => {
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_can_modify_account, null);
  MessageEvent2.removeMsgEvent(
    NetMsgType.msgType.msg_notify_open_or_close_withdraw_password,
    null
  );
  MessageEvent2.removeMsgEvent(
    NetMsgType.msgType.msg_notify_reset_account_password,
    null
  );
  MessageEvent2.removeMsgEvent(
    NetMsgType.msgType.msg_notify_bind_or_modify_withdraw_password,
    null
  );
});
</script>

<style lang="scss" scoped>
@import url(./style.scss);

.bind_container {
  height: 300px;

  .btn_submit {
    height: 44px;
    width: 100%;
    border-radius: 8px;
    margin-top: 16px;
  }
}

.security_settings {
  // background-image: url(/imgs/common/bg_img.webp);
  // background-size: 100% 100%;
  // background-color: #000000;
  height: calc(100vh - 100px);
  margin-top: 10px;
  padding: 10px 25px;
  overflow-y: auto;
  padding-bottom: 100px;

  .items {
    margin-bottom: 20px;

    > span {
      display: inline-block;
      margin-bottom: 9px;
      color: #fff;
    }

    > div {
      padding: 0 5px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;

      > span {
        height: 45px;
        flex: 2;

        padding: 12px 32px 12px 13px;
        border-radius: 8px;
        background: var(---, #1d1c3c);
        box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
      }

      > div {
        display: flex;
        flex: 1;
        align-items: center;

        .bind_btn {
          flex: 1;
          height: 44px;
          display: flex;
          margin-left: 10px;
          justify-content: center;
          align-items: center;
          color: #fff;
          width: 110px;
          border-radius: 8px;
          background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
        }
      }
    }
  }
}
</style>
